package cool.zhoujie.util;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.HttpURLConnection;

import cool.zhoujie.Constant;

public class HttpUtil {

    private static StringBuilder response;

    public static void sendHttpRequest(String address, HttpResponse httpResponse) {
        Log.d(Constant.TAG_NET, "开始发送网络请求");
        httpResponse.showLoading();
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(address);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(8 * 1000);
            connection.setReadTimeout(8 * 1000);
            InputStream in = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(in));
            response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (Exception e) {
            LogTool.log("网络请求错误");
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
                httpResponse.onResponse(response.toString());
            }
        }
    }

}
